from fastapi import APIRouter
from ..schemas import LoginRequest, UserInSchema, UserSchema
from src.utils.common_exception import LoginException
from src.utils.common_response import APIResponse, PaginationResponse
from ..core import create_access_token, authenticate_user
from ..models import UserInfo, Roles, Job
from fastapi import Depends
from ..core import get_current_user
from ..query_params import PaginationQueryParams, UserQueryParams
from ..schemas import UserSchema
from typing import List

router = APIRouter()


@router.post("/login", description="登录接口")
async def login(login_request: LoginRequest):
    user: UserInfo = await authenticate_user(login_request.username, login_request.password)
    if not user:
        raise LoginException()
    token = create_access_token(data={'username': user.username})
    return APIResponse(username=user.username, avatar=user.avatar, token=token)


@router.get("/users", description="查询所有用户")
async def get_user_list(
        page_query: PaginationQueryParams = Depends(),
        user_query: UserQueryParams = Depends(),
        # user: UserInfo = Depends(get_current_user)
):
    search = user_query.to_query_params()
    search["is_delete"] = False
    users = await UserInfo.filter(**search).filter(is_delete=False).all().prefetch_related("roles", 'dept', 'job')
    user_dicts = [await UserSchema.from_common_orm(user) for user in users]
    return PaginationResponse(data=user_dicts, page=page_query.page, page_size=page_query.page_size)


@router.get("/user/{user_id}", description='查询单个用户')
async def get_user_info(user_id: int):
    user = await UserInfo.filter(id=user_id, is_delete=False).prefetch_related("roles", 'dept', 'job').first()
    if user:
        user_dict = await UserSchema.from_common_orm(user)
        return APIResponse(result=user_dict)
    else:
        raise Exception('该用户不存在或已被删除')


@router.delete("/users", description='删除单个或者多个用户')
async def delete_user(ids: List[int]):
    user = await UserInfo.filter(id__in=ids).update(is_delete=True)
    print(user)
    return APIResponse(msg='删除成功')


@router.post('/users', description='新增用户接口')
async def create_user(user_in: UserInSchema):
    roles = user_in.roles or []
    jobs = user_in.job or []
    del user_in.roles
    del user_in.job
    password = UserInfo.make_password('123456')
    user_new = await UserInfo.create(**user_in.dict(), password=password)
    for role_id in roles:
        role = await Roles.get(id=role_id)
        await user_new.roles.add(role)
    for job_id in jobs:
        job = await Job.get(id=job_id)
        await user_new.job.add(job)
    return APIResponse(msg='创建成功')


@router.put('/users/{user_id}', description='修改用户')
async def update_user(user_id: int, user_in: UserInSchema):
    roles = user_in.roles or []
    jobs = user_in.job or []
    del user_in.roles
    del user_in.job

    await UserInfo.filter(id=user_id).update(**user_in.dict())
    user_new = await UserInfo.get(id=user_id)
    await user_new.roles.clear()
    await user_new.job.clear()
    for role_id in roles:
        role = await Roles.get(id=role_id)
        await user_new.roles.add(role)
    for job_id in jobs:
        job = await Job.get(id=job_id)
        await user_new.job.add(job)
    return APIResponse(msg='创建成功')


@router.post('/reset/password/{user_id}', description="重置密码")
async def reset_password(user_id: int, ):
    await UserInfo.filter(id=user_id).update(password=UserInfo.make_password('123456'))
    return APIResponse(msg='密码重置成功')


@router.delete('/lock', description="锁定用户")
async def lock_user(ids: List[int]):
    await UserInfo.filter(id__in=ids).update(is_active=False)
    return APIResponse(msg='锁定成功')
